//
//  LZCustomerCheckoutViewController.m
//  laziz_Merchant
//
//  Created by xbn_iMac on 2016/12/20.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LZCustomerCheckoutViewController.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "UINavigationController+FDFullscreenPopGesture.h"
#import "LZCustomerCheckoutHeaderView.h"
#import "LZAlertView.h"
#import "LZDateFormatterManager.h"
#import "LZCustomerCheckoutPresenter.h"
#import "LZScanQRCodeModel.h"
#import "LZCustomerCheckoutModel.h"
#import "LZCouponModel.h"
#import "LZGrouponModel.h"
#import "LZUserInfoView.h"
#import "LZUserModel.h"

// ********************* coupon cell *********************
#import "LZGrabCouponDetailMealsTimeCell.h"
#import "LZGrabCouponDetailOrderRulesCell.h"
#import "LZGrabCouponDetailRulesOfUseCell.h"

// ********************* group cell *********************
#import "LZFightGroupDetailOrderRulesCell.h"
#import "LZFightGroupDetailRulesOfUseCell.h"
#import "LZFightGroupDetailMealsTimeCell.h"
#import "LZVideoPublisherCell.h"

// &&&&&&&&&&&&&&&&&&&&& coupon type cell identifier &&&&&&&&&&&&&&&&&&&&&
static NSString *kCoupon_RulesOfUseCell = @"coupon_rulesOfUseCell";
static NSString *kCoupon_MealsTimeCell  = @"coupon_mealsTimeCell";
static NSString *kCoupon_PubliserCell = @"coupon_publisherCell";

// &&&&&&&&&&&&&&&&&&&&& group type cell identifier &&&&&&&&&&&&&&&&&&&&&
static NSString *kGroup_OrderRulesCell = @"group_orderRulesCell";
static NSString *kGroup_RulesOfUseCell = @"group_rulesOfUseCell";
static NSString *kGroup_MealsTimeCell  = @"group_mealsTimeCell";
static NSString *kGroup_PublisherCell  = @"group_publisherCell";

@interface LZCustomerCheckoutViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (weak, nonatomic) IBOutlet UITableView *table;
@property (weak, nonatomic) IBOutlet UIButton *confirmButton;

@property (strong, nonatomic) LZMerchantInfoModel *merchantInfoModel;

@property (strong, nonatomic) LZCustomerCheckoutPresenter *customerCheckoutPresenter;
@property (copy, nonatomic) NSString *orderId;
@property (strong, nonatomic) LZCustomerCheckoutModel *orderModel;

@end

@implementation LZCustomerCheckoutViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.umLogPageViewName = @"客户结账页面";
    
    self.title = LZLocalizedString(@"home_menu_customer_checkout", nil);
    
    self.navigationItem.hidesBackButton = YES;
    
    [self configBaseData];
    
    [self showSubviews:NO];
    
    // 优惠券  1 团购2
    if ([self.scanModel.promotionType isEqualToString:@"1"]) {
        [self registerCouponCell];
    }
    else if ([self.scanModel.promotionType isEqualToString:@"2"]) {
        [self registerGroupCell];
    }
    
    [self requestProductOrderId];
    
    // Do any additional setup after loading the view from its nib.
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = NO;
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    self.navigationController.fd_fullscreenPopGestureRecognizer.enabled = YES;
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - request

/* 生成订单号接口 */
- (void)requestProductOrderId {
    WS(weakSelf)
    [self.customerCheckoutPresenter getOrderNoOnSuccess:^(id data) {
        if (data) {
            weakSelf.orderId = [data copy];
            [weakSelf requestProductOrder];
        }
        else {
            [weakSelf showGenerateOrderErrorAlert];
        }
        
    } onFail:^(NSString *fail) {
        [weakSelf showGenerateOrderErrorAlert];
    }];
}

/* 生成订单接口 */
- (void)requestProductOrder {
    
    WS(weakSelf)
    
    [self.customerCheckoutPresenter productOrderWithConsumerId:self.scanModel.userId andOrderId:self.orderId andDisCountId:self.scanModel.disCountId andPromotionType:self.scanModel.promotionType andUserDevice:self.scanModel.deviceId onSuccess:^(id data) {
        weakSelf.orderModel = data;
        
        [weakSelf showSubviews:YES];
        
        NSString *couponName;   // 优惠名称（优惠券或团购的）
    
        if ([weakSelf.scanModel.promotionType isEqualToString:@"1"]) {
            // 优惠券
            couponName = weakSelf.orderModel.coupons.couponsName;
        }
        else if ([weakSelf.scanModel.promotionType isEqualToString:@"2"]) {
            // 团购
            couponName = weakSelf.orderModel.groupon.grouponName;
        }
        [weakSelf createHeaderViewWithOrderId:weakSelf.orderId andCouponName:couponName];
        
        [weakSelf.table reloadData];
        
    } onFail:^(NSString *fail) {
        
        if ([fail isEqualToString:@"0400027"]) {
            // 距离上次使用时间不足三小时，不能再次使用
            [weakSelf showUsedCouponShortTimeErrorAlert];
        }
        else if ([fail isEqualToString:@"0400036"]) {
            // 商家优惠不在优惠时间内，不能使用
            [weakSelf showIninvalidTimeRange];
        }
        else {
            [weakSelf showCanNotUseThisCouponErrorAlert];
        }
    }];
}

#pragma mark - privite method

- (void)configBaseData {
    
    self.customerCheckoutPresenter = [[LZCustomerCheckoutPresenter alloc] init];
    
    self.merchantInfoModel = [LZUserModel Instance].merchantInfo;
    
    [self.confirmButton setTitle:LZLocalizedString(@"confirm", nil) forState:UIControlStateNormal];
}

- (void)createHeaderViewWithOrderId:(NSString*)orderId andCouponName:(NSString*)name {
    LZCustomerCheckoutHeaderView *headerView = [[LZCustomerCheckoutHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 189)];
    
    [headerView setOrderId:orderId andCouponName:name];

    self.table.tableHeaderView = headerView;
    
    WS(weakSelf)
    headerView.scanAgainButtonClickBlock = ^() {
        [weakSelf.navigationController popViewControllerAnimated:YES];
    };
}

- (void)showSubviews:(BOOL)isShow {
    self.table.hidden = !isShow;
    self.confirmButton.hidden = !isShow;
}

// 无法使用此优惠，请重新扫描
- (void)showCanNotUseThisCouponErrorAlert {
    LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"checkout_cannot_use_promotion_remind", nil) andImage:nil cancelButtonTitle:nil otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
    [alert show];
    
    WS(weakSelf)
    alert.clickButtonIndexBlock = ^(NSInteger index) {
        [weakSelf.navigationController popViewControllerAnimated:YES];
    };
}

// 生成订单失败，因为距离用户上次优惠买单时间太短
- (void)showUsedCouponShortTimeErrorAlert {
    LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"checkout_short_time_remind", nil) andImage:nil cancelButtonTitle:nil otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
    [alert show];
    
    WS(weakSelf)
    alert.clickButtonIndexBlock = ^(NSInteger index) {
        [weakSelf.navigationController popViewControllerAnimated:YES];
    };
}

// 生成订单失败,商家优惠不在优惠时间内，不能使用
- (void)showIninvalidTimeRange {
    LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"checkout_invalid_time_range", nil) andImage:nil cancelButtonTitle:nil otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
    [alert show];
    
    WS(weakSelf)
    alert.clickButtonIndexBlock = ^(NSInteger index) {
        [weakSelf.navigationController popViewControllerAnimated:YES];
    };
}


// 生成订单失败，请重新扫描二维码
- (void)showGenerateOrderErrorAlert {
    LZAlertView *alert = [[LZAlertView alloc] initWithContent:LZLocalizedString(@"checkout_generate_order_failed_remind", nil) andImage:nil cancelButtonTitle:nil otherButtonTitles:LZLocalizedString(@"confirm", nil),nil];
    [alert show];
    
    WS(weakSelf)
    alert.clickButtonIndexBlock = ^(NSInteger index) {
        [weakSelf.navigationController popViewControllerAnimated:YES];
    };
}

#pragma mark - Event
- (IBAction)confirmButtonClickAction:(UIButton *)sender {
    [self.navigationController popToRootViewControllerAnimated:YES];
}


#pragma mark - UITableViewDelegate,UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.orderModel == nil) {
        return 0;
    }
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    // 优惠券  1 团购2
    if ([self.scanModel.promotionType isEqualToString:@"1"]) {
        return [self coupon_tableView:tableView numberOfRowsInSection:section];
    }
    else if ([self.scanModel.promotionType isEqualToString:@"2"]) {
        return [self group_tableView:tableView numberOfRowsInSection:section];
    }
    
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 优惠券  1 团购2
    if ([self.scanModel.promotionType isEqualToString:@"1"]) {
        return [self coupon_tableView:tableView heightForRowAtIndexPath:indexPath];
    }
    else if ([self.scanModel.promotionType isEqualToString:@"2"]) {
        return [self group_tableView:tableView heightForRowAtIndexPath:indexPath];
    }
    
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {

    return 10;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 优惠券  1 团购2
    if ([self.scanModel.promotionType isEqualToString:@"1"]) {
        return  [self coupon_tableView:tableView cellForRowAtIndexPath:indexPath];
    }
    else if ([self.scanModel.promotionType isEqualToString:@"2"]) {
        return [self group_tableView:tableView cellForRowAtIndexPath:indexPath];
    }
    
    return nil;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - coupon type tableView data source

- (void)registerCouponCell
{
    [self.table registerNib:[UINib nibWithNibName:@"LZGrabCouponDetailRulesOfUseCell" bundle:nil] forCellReuseIdentifier:kCoupon_RulesOfUseCell];
    [self.table registerNib:[UINib nibWithNibName:@"LZGrabCouponDetailMealsTimeCell" bundle:nil] forCellReuseIdentifier:kCoupon_MealsTimeCell];
    [self.table registerNib:[UINib nibWithNibName:@"LZVideoPublisherCell" bundle:nil] forCellReuseIdentifier:kCoupon_PubliserCell];
}

- (NSInteger)coupon_tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}

- (CGFloat)coupon_tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    WS(weakSelf)
    switch (indexPath.row) {

        case 0:
            if (self.orderModel.coupons.couponsRemindRule.length == 0 && self.orderModel.coupons.couponsUseConditions.length == 0) {
                return 0;
            }
            return [tableView fd_heightForCellWithIdentifier:kCoupon_RulesOfUseCell configuration:^(id cell) {
                LZGrabCouponDetailRulesOfUseCell *cellTemp = (LZGrabCouponDetailRulesOfUseCell *)cell;
                [cellTemp loadTitle:@"terms of use" contentStr:weakSelf.orderModel.coupons.couponsUseConditions guizeContent:weakSelf.orderModel.coupons.couponsRemindRule];
            }];
            break;
        case 1:
            return [tableView fd_heightForCellWithIdentifier:kCoupon_MealsTimeCell configuration:^(id cell) {
                LZGrabCouponDetailMealsTimeCell *cellTemp = (LZGrabCouponDetailMealsTimeCell *)cell;
                NSString *everyDayValid = [weakSelf.orderModel.coupons getCouponEverydayValid];

                [cellTemp loadCouponValidityPeriod:[NSString stringWithFormat:@"%@ - %@",[[LZDateFormatterManager shareInstance] stringFromDoubleTimestampHavePointyyyyMMdd:weakSelf.orderModel.coupons.couponsStartTime],[[LZDateFormatterManager shareInstance] stringFromDoubleTimestampHavePointyyyyMMdd:weakSelf.orderModel.coupons.couponsEndTime]]
                    ValidExcept:weakSelf.orderModel.coupons.couponsExceptTime
                    EverydayValid:everyDayValid
                    otherContent:weakSelf.orderModel.coupons.couponsRemindAppoint];
            }];
            break;
        case 2:
            return [tableView fd_heightForCellWithIdentifier:kCoupon_PubliserCell configuration:^(id cell) {
                LZVideoPublisherCell *cellTemp = (LZVideoPublisherCell *)cell;
                [cellTemp loadPublisherName:weakSelf.merchantInfoModel.restaurantName];
            }];
            break;
            
        default:
            break;
    }
    return 0;
}

- (UITableViewCell *)coupon_tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.row) {
        case 0:{
            LZGrabCouponDetailRulesOfUseCell *cell = [tableView dequeueReusableCellWithIdentifier:kCoupon_RulesOfUseCell];
            
            if (self.orderModel.coupons.couponsRemindRule.length == 0 && self.orderModel.coupons.couponsUseConditions.length == 0) {
                [cell loadTitle:@"" contentStr:@"" guizeContent:@""];

            }
            else {
                [cell loadTitle:@"terms of use" contentStr:self.orderModel.coupons.couponsUseConditions guizeContent:self.orderModel.coupons.couponsRemindRule];
            }
            
            return cell;
        }
            
            break;
        case 1:{
            LZGrabCouponDetailMealsTimeCell *cell = [tableView dequeueReusableCellWithIdentifier:kCoupon_MealsTimeCell];
            NSString *everyDayValid = [self.orderModel.coupons getCouponEverydayValid];

            [cell loadCouponValidityPeriod:[NSString stringWithFormat:@"%@ - %@",[[LZDateFormatterManager shareInstance] stringFromDoubleTimestampHavePointyyyyMMdd:self.orderModel.coupons.couponsStartTime],[[LZDateFormatterManager shareInstance] stringFromDoubleTimestampHavePointyyyyMMdd:self.orderModel.coupons.couponsEndTime]]
            ValidExcept:self.orderModel.coupons.couponsExceptTime
            EverydayValid:everyDayValid
            otherContent:self.orderModel.coupons.couponsRemindAppoint];
            return cell;
        }
            
            break;
        case 2:{
            LZVideoPublisherCell *cell = [tableView dequeueReusableCellWithIdentifier:kCoupon_PubliserCell];
            [cell loadPublisherName:self.merchantInfoModel.restaurantName];
            return cell;
        }
            
            break;
            
        default:
            break;
    }
    
    return nil;
}

#pragma mark - group type tableView data source

- (void)registerGroupCell
{
    [self.table registerNib:[UINib nibWithNibName:@"LZFightGroupDetailOrderRulesCell" bundle:nil] forCellReuseIdentifier:kGroup_OrderRulesCell];
    [self.table registerNib:[UINib nibWithNibName:@"LZFightGroupDetailRulesOfUseCell" bundle:nil] forCellReuseIdentifier:kGroup_RulesOfUseCell];
    [self.table registerNib:[UINib nibWithNibName:@"LZFightGroupDetailMealsTimeCell" bundle:nil] forCellReuseIdentifier:kGroup_MealsTimeCell];
    [self.table registerNib:[UINib nibWithNibName:@"LZVideoPublisherCell" bundle:nil] forCellReuseIdentifier:kGroup_PublisherCell];
    
}

- (NSInteger)group_tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 4;
}

- (CGFloat)group_tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    WS(weakSelf)
    switch (indexPath.row) {

        case 0:
            return [tableView fd_heightForCellWithIdentifier:kGroup_OrderRulesCell configuration:^(id cell) {
                LZFightGroupDetailOrderRulesCell *cellTemp = (LZFightGroupDetailOrderRulesCell *)cell;
                [cellTemp loadMembersNum:[NSString stringWithFormat:@"%ld",weakSelf.orderModel.groupon.grouponCount]
                FinishedTime:[[LZDateFormatterManager shareInstance] stringFromDoubleTimestampHavePointyyyyMMdd:weakSelf.orderModel.groupon.grouponEndTime]];
            }];
            break;
        case 1:
            return [tableView fd_heightForCellWithIdentifier:kGroup_RulesOfUseCell configuration:^(id cell) {
                LZFightGroupDetailRulesOfUseCell *cellTemp = (LZFightGroupDetailRulesOfUseCell *)cell;
                [cellTemp loatGrouponName:@"" RulesContent:weakSelf.orderModel.groupon.grouponRemindRule ExpirationTime:[[LZDateFormatterManager shareInstance] stringFromDoubleTimestampHavePointyyyyMMdd:weakSelf.orderModel.groupon.grouponDeadline]];
            }];
            break;
        case 2:
            return [tableView fd_heightForCellWithIdentifier:kGroup_MealsTimeCell configuration:^(id cell) {
                LZFightGroupDetailMealsTimeCell *cellTemp = (LZFightGroupDetailMealsTimeCell *)cell;
                NSString *everyDayValid = [weakSelf.orderModel.groupon getGroupEverydayValid];
                
                [cellTemp loadValidExcept:weakSelf.orderModel.groupon.grouponExceptTime
                EverydayValid:everyDayValid
                otherContent:weakSelf.orderModel.groupon.grouponRemindAppoint];
            }];
            break;
        case 3:
            return [tableView fd_heightForCellWithIdentifier:kGroup_PublisherCell configuration:^(id cell) {
                LZVideoPublisherCell *cellTemp = (LZVideoPublisherCell *)cell;
                [cellTemp loadPublisherName:weakSelf.merchantInfoModel.restaurantName];
            }];
            break;
            
        default:
            break;
    }
    
    return 0;
    
}

- (UITableViewCell *)group_tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    switch (indexPath.row) {
        case 0:{
            LZFightGroupDetailOrderRulesCell *cell = [tableView dequeueReusableCellWithIdentifier:kGroup_OrderRulesCell];
            [cell loadMembersNum:[NSString stringWithFormat:@"%ld",(long)self.orderModel.groupon.grouponCount]
            FinishedTime:[[LZDateFormatterManager shareInstance] stringFromDoubleTimestampHavePointyyyyMMdd:self.orderModel.groupon.grouponEndTime]];
            return cell;
        }
            
            break;
        case 1:{
            LZFightGroupDetailRulesOfUseCell *cell = [tableView dequeueReusableCellWithIdentifier:kGroup_RulesOfUseCell];
            [cell loatGrouponName:@"" RulesContent:self.orderModel.groupon.grouponRemindRule ExpirationTime:[[LZDateFormatterManager shareInstance] stringFromDoubleTimestampHavePointyyyyMMdd:self.orderModel.groupon.grouponDeadline]];

            return cell;
        }
            
            break;
        case 2:{
            LZFightGroupDetailMealsTimeCell *cell = [tableView dequeueReusableCellWithIdentifier:kGroup_MealsTimeCell];
            NSString *everyDayValid = [self.orderModel.groupon getGroupEverydayValid];
            [cell loadValidExcept:self.orderModel.groupon.grouponExceptTime
            EverydayValid:everyDayValid
            otherContent:self.orderModel.groupon.grouponRemindAppoint];
            return cell;
        }
            
            break;
        case 3:{
            LZVideoPublisherCell *cell = [tableView dequeueReusableCellWithIdentifier:kGroup_PublisherCell];
            [cell loadPublisherName:self.merchantInfoModel.restaurantName];
            return cell;
        }
            
            break;
            
        default:
            break;
    }
    
    return nil;
}

@end
